﻿Imports Microsoft.Win32
Imports Microsoft.VisualBasic
Imports System.Math

Public Class frmScr
    Dim imagenes As New List(Of Imagen)
    Dim t As Twitterizer.Framework.Twitter
    Dim renglones As Integer = 9
    Dim col1, col2, col3, col4 As frmCnfg.Listas
#Region "Metodos de ventana para cerrar"
    Private Sub frmScr_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        'Restore the mouse cursor.
        Dim tmplng As Integer
        Cursor.Show()

        'Re-enable the CTRL+ALT+DEL key combination if it is disabled.
        tmplng = SystemParametersInfo(SPI_SCREENSAVERRUNNING, 0&, 0&, 0&)

    End Sub

    Private Sub frmScr_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Me.Close()
    End Sub



    Private Sub frmScr_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove, lblSinConexion.MouseMove
        Static OldX As Integer
        Static OldY As Integer

        'Determines whether the mouse was moved and whether the movement was large.
        'If so, the screen saver is ended.
        If (OldX > 0 And OldY > 0) And (Math.Abs(e.X - OldX) > 3 Or Math.Abs(e.Y - OldY) > 3) Then
            Me.Close()

        End If
        'Assigns the current X and Y locations to OldX and OldY.
        OldX = e.X
        OldY = e.Y

    End Sub

#End Region

    
    Private Sub frmScr_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Dim newkey As RegistryKey = key.CreateSubKey("TwittScreenSaver")
        'Dim newkey As RegistryKey = key.CreateSubKey("Twit Screen Saver")
        'Dim user As String = newkey.GetValue("Usuario")
        t = New Twitterizer.Framework.Twitter(newkey.GetValue("Usuario"), newkey.GetValue("Pwd"))
        col1 = newkey.GetValue("Col1")
        col2 = newkey.GetValue("Col2")
        col3 = newkey.GetValue("Col3")
        col4 = newkey.GetValue("Col4")
        Dim refresh As Integer = newkey.GetValue("refresh")
        If refresh = 0 Then refresh = 5
        Timer1.Interval = refresh * 60000
        newkey.Close()

        lblCol1.Text = ObtenerTexto(col1)
        lblCol2.Text = ObtenerTexto(col2)
        lblCol3.Text = ObtenerTexto(col3)
        lblCol4.Text = ObtenerTexto(col4)
        Cursor.Hide()
        Timer1_Tick(Me, Nothing)
    End Sub

    Private Function ObtenerTexto(ByVal col As frmCnfg.Listas) As String
        Select Case col
            Case frmCnfg.Listas.DirectMessages
                Return "Mensajes Directos"
            Case frmCnfg.Listas.Friends
                Return "Amigos"
            Case frmCnfg.Listas.None
                Return ""
            Case frmCnfg.Listas.PublicTimeline
                Return "Timeline Público"
            Case frmCnfg.Listas.Reply
                Return "Replies"
            Case frmCnfg.Listas.User
                Return "Mis Twitts"
            Case Else
                Return ""
        End Select
    End Function

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        RegeneraTabla(tlpColuma1, ObtenerStatuses(col1))
        Application.DoEvents()
        RegeneraTabla(tlpColumna2, ObtenerStatuses(col2))
        Application.DoEvents()
        RegeneraTabla(tlpColumna3, ObtenerStatuses(col3))
        Application.DoEvents()
        RegeneraTabla(tlpColumna4, ObtenerStatuses(col4))
        Application.DoEvents()
        'RegeneraTabla(Me.tlpColuma1, col)

        CargarImagenes(tlpColuma1)
        Application.DoEvents()
        CargarImagenes(tlpColumna2)
        Application.DoEvents()
        CargarImagenes(tlpColumna3)
        Application.DoEvents()
        CargarImagenes(tlpColumna4)
        Application.DoEvents()
    End Sub

    Private Sub CargarImagenes(ByVal tabla As TableLayoutPanel)
        For Each Control As Twitt In tabla.Controls
            If Control.ImagenUsuario.Imagen Is Nothing Then

                Dim img As Image = BuscarImagen(Control.ImagenUsuario.IdUsuario)
                If img Is Nothing Then img = LoadWebImage(Control.ImagenUsuario.UrlImagen)
                Control.ImagenUsuario.Imagen = img
                Control.pbImagen.Image = Control.ImagenUsuario.Imagen
                Control.Hide()
                Control.Show()
                imagenes.Add(Control.ImagenUsuario)

                Application.DoEvents()
            End If
            Application.DoEvents()
        Next
    End Sub

    Private Function BuscarImagen(ByVal idUsuario As Integer) As Image
        Dim ret As Image = Nothing
        For Each img As Imagen In imagenes
            If img.IdUsuario = idUsuario Then
                ret = img.Imagen
                Exit For
            End If
        Next
        Return ret
    End Function

    Private Function ObtenerStatuses(ByVal tipo As frmCnfg.Listas) As Twitterizer.Framework.TwitterStatusCollection
        Dim ret As New Twitterizer.Framework.TwitterStatusCollection()

        Try
            Select Case tipo
                Case frmCnfg.Listas.DirectMessages
                    ret = t.DirectMessages.DirectMessages()
                Case frmCnfg.Listas.Friends
                    ret = t.Status.FriendsTimeline()
                Case frmCnfg.Listas.None
                Case frmCnfg.Listas.PublicTimeline
                    ret = t.Status.PublicTimeline
                Case frmCnfg.Listas.Reply
                    ret = t.Status.Replies
                Case frmCnfg.Listas.User
                    ret = t.Status.UserTimeline()
            End Select
            lblSinConexion.Visible = False
        Catch ex As Twitterizer.Framework.TwitterizerException
            If ex.Message = "No se puede resolver el nombre remoto: 'twitter.com'" Then
                lblSinConexion.Visible = True
            ElseIf ex.Message = "Error Parsing Twitter Response." Then
                lblSinConexion.Text = ex.Message
                lblSinConexion.Visible = True
            Else
                ret = t.Status.PublicTimeline()
                lblSinConexion.Visible = False
            End If

        Catch ex As Exception
            lblSinConexion.Visible = True
        End Try
        
        Return ret
    End Function


    Private Sub RegeneraTabla(ByRef tabla As TableLayoutPanel, ByVal status As Twitterizer.Framework.TwitterStatusCollection)
        While tabla.Controls.Count > 0
            tabla.Controls.RemoveAt(0)
        End While

        For x As Integer = 0 To renglones - 1
            If x >= status.Count Then Exit For
            tabla.Controls.Add(GenerarTwitt(status(x)), 0, x)
            Application.DoEvents()
        Next

    End Sub

    Private Function GenerarTwitt(ByVal status As Twitterizer.Framework.TwitterStatus) As Twitt
        Dim ret As New Twitt
        ret.Usuario = status.TwitterUser.ScreenName
        ret.Texto = SustituyeHTML(status.Text)
        ret.ImagenUsuario.IdUsuario = status.TwitterUser.ID

        AddHandler ret.KeyDown, AddressOf frmScr_KeyDown
        AddHandler ret.MouseMove, AddressOf frmScr_MouseMove

        If status.TwitterUser.ProfileImageUri IsNot Nothing Then ret.ImagenUsuario.UrlImagen = status.TwitterUser.ProfileImageUri.AbsoluteUri
        For Each img As Imagen In imagenes
            If img.IdUsuario = status.TwitterUser.ID Then
                ret.ImagenUsuario = img
                Exit For
            End If
        Next
        'If status.TwitterUser.ProfileImageUri IsNot Nothing Then ret.imagen = LoadWebImage(status.TwitterUser.ProfileImageUri.AbsoluteUri)
        Return ret
    End Function


    Public Function LoadWebImage(ByVal ImageURL As String) As Image

        Dim objImage As IO.MemoryStream
        Dim objwebClient As System.Net.WebClient
        Dim sURL As String = Trim(ImageURL)
        Dim img As Image = Nothing
        Try
            If Not sURL.ToLower().StartsWith("http://") _
                 Then sURL = "http://" & sURL
            objwebClient = New Net.WebClient()
            objImage = New  _
               IO.MemoryStream(objwebClient.DownloadData(sURL))
            img = Image.FromStream(objImage)
        Catch ex As Exception

        End Try
        Return img
    End Function
End Class
